package com.mj.ipaddress.activity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.baidu.appx.BDBannerAd;
import com.baidu.appx.BDInterstitialAd;
import com.baidu.appx.BDBannerAd.BannerAdListener;
import com.baidu.appx.BDInterstitialAd.InterstitialAdListener;
import com.mj.ipaddress.R;
import com.mj.ipaddress.service.IPaddressService;
import com.mj.ipaddress.util.NetUtils;
import com.mj.ipaddress.util.RegUtil;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * IP地址查询
 * @author zhaominglei
 * @date 2015-3-11
 * 
 */
public class MainActivity extends Activity implements OnClickListener {
	private static final String TAG = MainActivity.class.getSimpleName();
	private IPaddressService ipService = new IPaddressService();
	private boolean isExit = false;
	private TimerTask timerTask;
	private EditText ipaddressText; //IP地址输入框
	private String ipaddress; //IP地址
	private Button queryBtn; //查询
	private ProgressBar queryProgressBar; //查询进度条
	private TextView resultView; //结果
	private Button appOffersButton; //推荐应用
	private RelativeLayout appxBannerContainer; //appx 容器
	private static BDBannerAd bannerAdView; //横幅广告
	private BDInterstitialAd appxInterstitialAdView; //插屏广告
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		init();
	}
	
	private void init() {
		ipaddressText = (EditText)findViewById(R.id.ipaddress_ipaddress_edt);
		queryBtn = (Button)findViewById(R.id.ipaddress_query_btn);
		queryProgressBar = (ProgressBar)findViewById(R.id.ipaddress_query_progressbar);
		resultView = (TextView)findViewById(R.id.ipaddress_result);
		appOffersButton = (Button)findViewById(R.id.appOffersButton);
		
		queryBtn.setOnClickListener(this);
		appOffersButton.setOnClickListener(this);
		
		//创建广告视图 发布时请使用正确的ApiKey和广告位ID
		bannerAdView = new BDBannerAd(this, "tZ1ywNh0YajW4vGq3yAASEGH",
				"G0IFkZcG6X1xuaD6g0nvmxGw");
		//设置横幅广告展示尺寸，如不设置，默认为SIZE_FLEXIBLE;
//						bannerAdView.setAdSize(BDBannerAd.SIZE_320X50);
		//设置横幅广告行为监听器
		bannerAdView.setAdListener(new BannerAdListener() {
			@Override
			public void onAdvertisementDataDidLoadFailure() {
				Log.e(TAG, "load failure");
			}
			@Override
			public void onAdvertisementDataDidLoadSuccess() {
				Log.e(TAG, "load success");
			}
			@Override
			public void onAdvertisementViewDidClick() {
				Log.e(TAG, "on click");
			}
			@Override
			public void onAdvertisementViewDidShow() {
				Log.e(TAG, "on show");
			}
			@Override
			public void onAdvertisementViewWillStartNewIntent() {
				Log.e(TAG, "leave app");
			}
		});
		appxBannerContainer = (RelativeLayout) findViewById(R.id.appx_banner_container);
		appxBannerContainer.addView(bannerAdView);
		
		//创建广告视图 发布时请使用正确的ApiKey和广告位ID
		appxInterstitialAdView = new BDInterstitialAd(this,
				"tZ1ywNh0YajW4vGq3yAASEGH", "DeOwzl7H6lDMU5ki2MwpYI0u");
		//设置插屏广告行为监听器
		appxInterstitialAdView.setAdListener(new InterstitialAdListener() {
			@Override
			public void onAdvertisementDataDidLoadFailure() {
				Log.e(TAG, "load failure");
			}
			@Override
			public void onAdvertisementDataDidLoadSuccess() {
				Log.e(TAG, "load success");
			}
			@Override
			public void onAdvertisementViewDidClick() {
				Log.e(TAG, "on click");
			}
			@Override
			public void onAdvertisementViewDidHide() {
				Log.e(TAG, "on hide");
			}
			@Override
			public void onAdvertisementViewDidShow() {
				Log.e(TAG, "on show");
			}
			@Override
			public void onAdvertisementViewWillStartNewIntent() {
				Log.e(TAG, "leave");
			}
		});
		//加载广告
		appxInterstitialAdView.loadAd();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.ipaddress_query_btn:
			resultView.setText("");
			ipaddress = ipaddressText.getText().toString();
			if (ipaddress == null || ipaddress.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.ipaddress_ipaddress_hint, Toast.LENGTH_SHORT).show();
				return;
			}
			if (!RegUtil.isIP(ipaddress)) {
				Toast.makeText(getApplicationContext(), R.string.ipaddress_error1, Toast.LENGTH_SHORT).show();
				return;
			}
			getIPaddressInfo();
			break;
			
		case R.id.appOffersButton:
			//展示插屏广告前先请先检查下广告是否加载完毕
			if (appxInterstitialAdView.isLoaded()) {
				appxInterstitialAdView.showAd();
			} else {
				Log.i(TAG, "AppX Interstitial Ad is not ready");
				appxInterstitialAdView.loadAd();
			}
			break;

		default:
			break;
		}
	}
	
	private void getIPaddressInfo() {
		if (NetUtils.isConnected(getApplicationContext())) {
			queryProgressBar.setVisibility(View.VISIBLE);
			new IPaddressInfoAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isExit) {
			MainActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}
	
	public class IPaddressInfoAsyncTask extends AsyncTask<String, String, List<String>> {
		@Override
		protected List<String> doInBackground(String... params) {
			return ipService.getIPaddressInfo(ipaddress);
		}

		@Override
		protected void onPostExecute(List<String> result) {
			queryProgressBar.setVisibility(View.GONE);
			if (result != null && !result.isEmpty()) {
				StringBuilder sb = new StringBuilder();
				for (String string : result) {
					sb.append(string).append("\n\n");
				}
				resultView.setText(sb.toString());
			} else {
				Toast.makeText(getApplicationContext(), R.string.ipaddress_error2, Toast.LENGTH_SHORT).show();
			}
		}
	}
}
